package es.spider.service;

import java.util.ArrayList;
import java.util.List;

import org.htmlparser.Node;
import org.htmlparser.Parser;
import org.htmlparser.Tag;
import org.htmlparser.filters.TagNameFilter;
import org.htmlparser.lexer.Lexer;
import org.htmlparser.tags.Bullet;
import org.htmlparser.tags.BulletList;
import org.htmlparser.tags.Div;
import org.htmlparser.tags.ImageTag;
import org.htmlparser.tags.LinkTag;
import org.htmlparser.tags.Span;
import org.htmlparser.tags.TableRow;
import org.htmlparser.tags.TableTag;
import org.htmlparser.util.NodeList;
import org.htmlparser.util.ParserException;
import org.htmlparser.util.SimpleNodeIterator;
import org.springframework.stereotype.Service;

import es.spider.dao.Enlace;
import es.spider.dao.Pelicula;

@Service("homeService")
public class HomeService {
	
	/**
	 * Parsea el html recuperando una lista de titulos
	 * 
	 * @param abono
	 * @return
	 */
	public List<Pelicula> parsea (String url) {
		
		List<Pelicula> lista = new ArrayList<Pelicula>();
		
		try {	
			Parser	parser = new Parser(url);
			//parser.setEncoding("UTF-8");
			NodeList aList = parser.extractAllNodesThatMatch (new TagNameFilter ("A"));
			SimpleNodeIterator aIt = aList.elements();
			Pelicula peli = null;
			while (aIt.hasMoreNodes()){
				Node node = aIt.nextNode();
				if (node.getText().contains("http://www.filmaffinity.com/es/film")){
					
					if (node.getFirstChild().getClass().getSimpleName().equals("TextNode")){
						String titulo = node.getFirstChild().getText().replaceAll("\r","").replaceAll("\n","").replaceAll("  ","");
						System.out.println("Titulo ["+titulo+"]");
						peli.setTitulo(titulo);
						
						TableTag table = (TableTag)node.getParent().getParent().getParent();
						Lexer lex = new Lexer(table.getChildrenHTML());
						Parser actorParser = new Parser (lex);
						NodeList actorList = actorParser.extractAllNodesThatMatch(new TagNameFilter("DIV"));
						if (actorList.size()>0){
							Node n = actorList.elementAt(0);
							String actores = formaliza(n.getFirstChild().getText()).replace(", ",",");
							System.out.println("Actores ["+actores+"]");
							String[] s = actores.split(",");
							for (String nombre:s){
								peli.getActores().add(nombre);	
							}
							lista.add(peli);
						}
						
					}else if (node.getFirstChild().getClass().getSimpleName().equals("ImageTag")){
						peli = new Pelicula();
						peli.setActores(new ArrayList<String>());
						Tag portada = (Tag)node.getFirstChild();
						System.out.println("----------------------------------------------");
						System.out.println("Portada ["+portada.getAttribute("src")+"]");
						peli.setUrlPortada(portada.getAttribute("src"));
					}
				}	
			}
		} catch (ParserException e) {
			e.printStackTrace();
		}
		
		return lista; 
	}
	
	/**
	 * Parsea el html recuperando una lista de titulos
	 * 
	 * @param abono
	 * @return
	 */
	public Pelicula parseaDetalle (String url) {
		
		Pelicula peli = new Pelicula();
		
		try {	
			Parser	parser = new Parser(url);
			parser.setEncoding("UTF-8");
			NodeList aList = parser.extractAllNodesThatMatch (new TagNameFilter ("A"));
			SimpleNodeIterator aIt = aList.elements();
			while (aIt.hasMoreNodes()){
				Node node = aIt.nextNode();
				if (node.getText().contains("http://www.filmaffinity.com/es/evideos.php?movie_id=")){
					System.out.println("Tipo ["+node.getFirstChild().getClass().getSimpleName()+"] Texto["+node.getFirstChild().getText()+"]");
					TableTag table = (TableTag)node.getParent().getParent().getParent().getParent().getParent().getParent();
					Lexer lex = new Lexer(table.getChildrenHTML());
					Parser tdParser = new Parser (lex);
					NodeList actorList = tdParser.extractAllNodesThatMatch(new TagNameFilter("TD"));
					SimpleNodeIterator it = actorList.elements();
					while (it.hasMoreNodes()){
						Node n = it.nextNode();	
						if (n.getFirstChild()!=null){
							if (n.getFirstChild().getClass().getSimpleName().equals("TagNode")){
								if (n.getFirstChild().getNextSibling().getText().contains("ORIGINAL")){
									Node titulo = it.nextNode();
									peli.setTituloOriginal(titulo.getFirstChild().getNextSibling().getText());
								}else if (n.getFirstChild().getNextSibling().getText().contains("AÑO")){
									Node aux = it.nextNode();
									Node anio = it.nextNode();
									peli.setAnio(anio.getFirstChild().getText());
									System.out.println("AÑO ["+anio.getFirstChild().getText()+"]");
								}else if (n.getFirstChild().getNextSibling().getText().contains("DURACIÓN")){
									Node aux = it.nextNode();
									Node dur = it.nextNode();
									peli.setDuracion(dur.getFirstChild().getText());
									System.out.println("DURACION ["+dur.getFirstChild().getText()+"]");
								}else if (n.getFirstChild().getNextSibling().getText().contains("DIRECTOR")){
									Node ndirector = it.nextNode();
									String director = formaliza(ndirector.getFirstChild().getFirstChild().getText());
									peli.setDirector(director);
									System.out.println("DIRECTOR ["+director+"]");
								}else if (n.getFirstChild().getNextSibling().getText().contains("GUIÓN")){
									Node nguion = it.nextNode();
									peli.setGuion(nguion.getFirstChild().getText());
									System.out.println("GUION ["+nguion.getFirstChild().getText()+"]");
								}else if (n.getFirstChild().getNextSibling().getText().contains("MÚSICA")){
									Node nmusica = it.nextNode();
									peli.setMusica(nmusica.getFirstChild().getText());
									System.out.println("MÚSICA ["+nmusica.getFirstChild().getText()+"]");
								}else if (n.getFirstChild().getNextSibling().getText().contains("FOTOGRAFÍA")){
									Node nfoto = it.nextNode();
									peli.setFotografia(nfoto.getFirstChild().getText());
									System.out.println("FOTOGRAFÍA ["+nfoto.getFirstChild().getText()+"]");
								}
							}
						}
					}
				}	
			}
		} catch (ParserException e) {
			e.printStackTrace();
		}
		return peli; 
	}

	public List<Enlace> buscaEnlacesSerie(Pelicula pelicula) {
		
		List<Enlace> enlaces = new ArrayList<Enlace>();
		// String url = buscarUrlPelicula(pelicula.getTitulo());
		String url = "C:\\Users\\rarba4h\\Desktop\\enlaces.html";
		
		try {	
			Parser	parser = new Parser(url);
			parser.setEncoding("UTF-8");
			NodeList ulList = parser.extractAllNodesThatMatch (new TagNameFilter ("UL"));
			SimpleNodeIterator aIt = ulList.elements();
			
			while (aIt.hasMoreNodes()){
				BulletList node = (BulletList)aIt.nextNode();
				Lexer lex = new Lexer(node.getChildrenHTML());
				Parser ulParser = new Parser (lex);
				NodeList aList = ulParser.extractAllNodesThatMatch(new TagNameFilter("A"));
				SimpleNodeIterator it = aList.elements();
				while (it.hasMoreNodes()){
					LinkTag n = (LinkTag) it.nextNode();
					String href = n.getAttribute("href");
					if (href.contains("http://www.seriesyonkis.com/capitulo")){
						Enlace enlace = new Enlace();
						enlace.setTitulo(formaliza(n.getFirstChild().getText()));
						enlace.setUrl(href);
						enlaces.add(enlace);
						System.out.println("Titulo ["+formaliza(n.getFirstChild().getText())+"] link["+href+"]");
					}
				}
			}
			
		} catch (ParserException e) {
			e.printStackTrace();
		}
		
		return enlaces;
	}
	
	
	public List<Enlace> buscaEnlacesPeli (Pelicula pelicula) {
		
		List<Enlace> enlaces = new ArrayList<Enlace>();
		String url = buscarUrlPelicula(pelicula.getTitulo());
		System.out.println("@@@@@@@@@@@@@  URL["+url+"]  @@@@@@@@@@@@@");
		try {	
			
			Parser	parser = new Parser(url);
			parser.setEncoding("UTF-8");
			NodeList ulList = parser.extractAllNodesThatMatch (new TagNameFilter ("TABLE"));
			SimpleNodeIterator aIt = ulList.elements();
			TableTag node = (TableTag)aIt.nextNode();
			Lexer lex = new Lexer(node.getChildrenHTML());
			Parser ulParser = new Parser (lex);
			NodeList trList = ulParser.extractAllNodesThatMatch(new TagNameFilter("TR"));
			SimpleNodeIterator trIt = trList.elements();				
			while (trIt.hasMoreNodes()){
				System.out.println("-----------------------------------------------------");
				Enlace enlace = new Enlace();
				TableRow trNode = (TableRow)trIt.nextNode();
				Lexer trlex = new Lexer(trNode.getChildrenHTML());
				Parser divParser = new Parser (trlex);
				NodeList divList = divParser.extractAllNodesThatMatch(new TagNameFilter("DIV"));
				SimpleNodeIterator divIt = divList.elements();
				while (divIt.hasMoreNodes()){
					Div divNode = (Div)divIt.nextNode();
					Lexer linklex = new Lexer(divNode.getChildrenHTML());
					Parser linkParser = new Parser (linklex);
					NodeList linkList = linkParser.extractAllNodesThatMatch(new TagNameFilter("A"));
					if (linkList.size()>0){
						LinkTag link = (LinkTag) linkList.elementAt(0);
						System.out.println("ENLACE ["+link.getAttribute("href")+"]");	
						enlace.setUrl(link.getAttribute("href"));
					} else {
						if (divNode.getChildren()!=null){
							if (divNode.getFirstChild().getClass()==Span.class){
								Span span = (Span)divNode.getFirstChild();
								if (span.getChildCount()>0 && span.getFirstChild().getClass()==ImageTag.class){
									ImageTag image = (ImageTag)span.getFirstChild();
									enlace.setCalidad(image.getAttribute("title"));
									System.out.println("CALIDAD ["+enlace.getCalidad()+"]");
								}else if (span.getChildrenHTML().contains("Duraci")){
									if (span.getChild(3).getText().equals("B")){
										enlace.setFormato(span.getChild(4).getText());
										System.out.println("FORMATO ["+span.getChild(4).getText()+"]");	
									}else if (span.getChild(3).getText().equals("BR")){
										enlace.setFormato(span.getChild(5).getText());
										System.out.println("FORMATO ["+span.getChild(5).getText()+"]");
									}else{
										enlace.setFormato(span.getChild(3).getText());;
										System.out.println("FORMATO ["+span.getChild(3).getText()+"]");
									}
									Div ripperNode = (Div)divIt.nextNode();
									String uploader = ripperNode.getFirstChild().getFirstChild().getText().equals("BR")?
												ripperNode.getFirstChild().getFirstChild().getNextSibling().getText():
												ripperNode.getFirstChild().getFirstChild().getText();
									System.out.println("UPLOADER ["+uploader+"]");
									enlace.setUploader(uploader);
								}
							}else if (divNode.getFirstChild().getClass()==ImageTag.class){
								ImageTag idioma = (ImageTag)divNode.getFirstChild();
								enlace.setIdioma(idioma.getAttribute("alt"));
								System.out.println("IDIOMA ["+idioma.getAttribute("alt")+"]");
							}
						}	
					}
				}
				enlaces.add(enlace);
			}
			
			
		} catch (ParserException e) {
			e.printStackTrace();
		}
		
		return enlaces;
	}
	
	
	
	private String formaliza (String texto){
		return texto.replaceAll("\n","").replaceAll("\r","").replaceAll("  ","").replace(", ",",");
	}
	
	
	private String buscarUrlPelicula(String titulo){
		
		System.out.println("-----------------------------------------------------");

		// TODO: En funcion del titulo modificar la url
		// if titulo.startWith("a") String url = "C:\\Users\\rarba4h\\Desktop\\enlacespa.html";
		// else if titulo.startWith("b") String url = "C:\\Users\\rarba4h\\Desktop\\enlacespb.html";
		// ...
		String url = "C:\\Users\\rarba4h\\Desktop\\enlacespk.html";

		try{
			Parser	parser = new Parser(url);
			parser.setEncoding("UTF-8");
			NodeList ulList = parser.extractAllNodesThatMatch (new TagNameFilter ("UL"));
			SimpleNodeIterator ulIt = ulList.elements();
			while (ulIt.hasMoreNodes()){
				BulletList ulNode = (BulletList)ulIt.nextNode();
				Lexer ullex = new Lexer(ulNode.getChildrenHTML());
				
				Parser liParser = new Parser (ullex);
				NodeList liList = liParser.extractAllNodesThatMatch(new TagNameFilter("LI"));
				
				SimpleNodeIterator liIt = liList.elements();
				while (liIt.hasMoreNodes()){
					Bullet ilNode = (Bullet)liIt.nextNode();
					if (ilNode.getChildCount()>1){
						if (ilNode.getChild(1).getClass()==LinkTag.class){
							LinkTag link = (LinkTag)ilNode.getChild(1);
							System.out.println("TITULO ["+link.getAttribute("title")+"]");
							System.out.println("URL ["+link.getAttribute("href")+"] ");
							if (link.getAttribute("href").contains(titulo)){
								return link.getAttribute("href");
							}
						}	
					}
				}
			}

		}catch (Exception e) {
			e.printStackTrace();
		}
		
		System.out.println("-----------------------------------------------------");
		return "C:\\Users\\rarba4h\\Desktop\\enlacesp1.html";
	}

}

